package mine.personal.demo.pratice.algorithm.dynamicprogramming.subarray;

import java.util.Arrays;

/**
 * @Author: lhl
 * @CreateTime: 2025-04-23
 * @Description: 动态规划--子数组合集
 * @Version: 1.0
 */
public class Solution {
    /**
     * leetcode -> 最大子数组和
     * @author: 李鸿麟
     * @date: 2025/4/23
     * @param: nums
     * @return: int
     */
    public int maxSubArray(int[] nums) {
        int n = nums.length;
        int[] dp = new int[n + 1];
        int ret = Integer.MIN_VALUE;
        for (int i = 1; i <= n; i++) {
            dp[i] = Math.max(dp[i - 1] + nums[i - 1], nums[i - 1]);
            ret = Math.max(ret, dp[i]);
        }
        return ret;
    }

    /**
     * leetcode -> 循环子数组的最大和
     * @author: 李鸿麟
     * @date: 2025/4/25
     * @param: nums
     * @return: int
     */
    public int maxSubarraySumCircular(int[] nums) {
        int n = nums.length;
        int[] f = new int[n + 1];
        int[] g = new int[n + 1];
        int sum = 0;
        int fmax = Integer.MAX_VALUE; int gmin = Integer.MAX_VALUE;
        for (int i = 1; i <= n ; i++) {
            int x = nums[i - 1];
            f[i] = Math.max(f[i - 1] + nums[i], x);
            fmax = Math.max(fmax, f[i]);
            g[i] = Math.min(g[i - 1] + nums[i], x);
            gmin = Math.min(g[i], gmin);
            sum += x;
        }
        return sum == gmin ? fmax : Math.max(fmax , sum - gmin);
    }
}
